//
//  ScencPrizeVC.m
//  SMTools
//
//  Created by fengsh on 2019/1/12.
//  Copyright © 2019年 fengsh. All rights reserved.
//

#import "ScencPrizeVC.h"
#import "ScenePrizes.h"
#import <Masonry/Masonry.h>
#import <MagicalRecord/MagicalRecord.h>
#import "LuckyUtils.h"
#import "ScencMembers.h"
#import "ScencResults.h"
#import "ScencScreenWND.h"

@interface ScencPrizeVC ()<NSTableViewDelegate,NSTableViewDataSource,NSMenuDelegate>
@property (weak) IBOutlet NSTableView       *tableview;
@property (weak) IBOutlet NSTextField       *tf_jiangpin;
@property (weak) IBOutlet NSComboBox        *cmb_name;
@property (weak) IBOutlet NSTextField       *tf_instruction;
@property (weak) IBOutlet NSComboBox        *cmb_total_count;
@property (weak) IBOutlet NSComboBox        *cmb_nums_of_per;
@property (weak) IBOutlet NSPopUpButton     *pb_select;
@property (weak) IBOutlet NSButton          *ckb_allows;

@property (nonatomic, strong) NSMutableArray    *dataset;

@property (nonatomic, strong) ScencScreenWND    *scnwnd;

@end

@implementation ScencPrizeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do view setup here.
    
    _dataset = [NSMutableArray array];
    
    NSMenu *tablemenu = [[NSMenu alloc]init];
    tablemenu.delegate = self;
    self.tableview.menu = tablemenu;
    
    [_pb_select removeAllItems];
    [_pb_select addItemWithTitle:@"全部"];
    [_pb_select addItemWithTitle:@"未开奖"];
    [_pb_select addItemWithTitle:@"已抽奖"];
    [_pb_select selectItemAtIndex:0];
    
    [_cmb_name removeAllItems];
    [_cmb_name addItemWithObjectValue:@"特等奖"];
    [_cmb_name addItemWithObjectValue:@"一等奖"];
    [_cmb_name addItemWithObjectValue:@"二等奖"];
    [_cmb_name addItemWithObjectValue:@"三等奖"];
    [_cmb_name addItemWithObjectValue:@"四等奖"];
    [_cmb_name addItemWithObjectValue:@"五等奖"];
    
    [_cmb_total_count removeAllItems];
    for (int i = 1; i < 6; i++) {
        [_cmb_total_count addItemWithObjectValue:@(i)];
    }
    [_cmb_total_count selectItemAtIndex:0];
    
    [_cmb_nums_of_per removeAllItems];
    [_cmb_nums_of_per addItemWithObjectValue:@"1"];
    [_cmb_nums_of_per addItemWithObjectValue:@"2"];
    [_cmb_nums_of_per addItemWithObjectValue:@"3"];
    [_cmb_nums_of_per addItemWithObjectValue:@"5"];
    [_cmb_nums_of_per addItemWithObjectValue:@"10"];
    [_cmb_nums_of_per selectItemAtIndex:0];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowWillClose:) name:NSWindowWillCloseNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onFreshData) name:@"kOpenLuckyFinish" object:nil];
}

- (void)viewWillAppear
{
    [super viewWillAppear];
    
    [self refreshAll];
}

- (void)onFreshData
{
    [self refreshAll];
}

- (void)refreshAll
{
    NSArray *arr =  [ScenePrizes MR_findAllSortedBy:@"prize_remain_count,createTime" ascending:NO];
    
    [_dataset removeAllObjects];
    if (arr) {
        [_dataset addObjectsFromArray:arr];
        
        [self.tableview reloadData];
    }
}

- (void)reset
{
    [_cmb_name setStringValue:@""];
    [_cmb_total_count selectItemAtIndex:0];
    [_cmb_nums_of_per setStringValue:@""];
    [_tf_jiangpin setStringValue:@""];
    [_tf_instruction setStringValue:@""];
    [_ckb_allows setState:NSControlStateValueOff];
}

- (IBAction)onSelectChanged:(NSPopUpButton*)sender
{
    NSArray *arr = nil;
    NSInteger idx = [sender indexOfSelectedItem];
    if (idx == 0) {
        arr = [ScenePrizes MR_findAllSortedBy:@"prize_remain_count,createTime" ascending:NO];
        
    } else if (idx == 1) {
        NSPredicate *pre = [NSPredicate predicateWithFormat:@"prize_remain_count > 0"];
        arr = [ScenePrizes MR_findAllSortedBy:@"createTime" ascending:NO withPredicate:pre];
    } else {
        NSPredicate *pre = [NSPredicate predicateWithFormat:@"prize_remain_count == 0"];
        arr = [ScenePrizes MR_findAllSortedBy:@"createTime" ascending:NO withPredicate:pre];
    }
    
    [_dataset removeAllObjects];
    [_dataset addObjectsFromArray:arr];
    [self.tableview reloadData];
}

- (IBAction)onClean:(id)sender
{
    NSAlert *alert = [[NSAlert alloc] init];
    [alert addButtonWithTitle:@"确定"];
    [alert addButtonWithTitle:@"取消"];
    [alert setMessageText:@"您确定要清空所有奖项吗？"];
    [alert setInformativeText:@"删除后将不可恢复哦!!!"];
    [alert setAlertStyle:NSWarningAlertStyle];
    [alert beginSheetModalForWindow:self.view.window completionHandler:^(NSInteger result) {
        if (result == NSAlertFirstButtonReturn) {
            [MagicalRecord saveWithBlock:^(NSManagedObjectContext * _Nonnull localContext) {
                [ScenePrizes MR_truncateAllInContext:localContext];
            } completion:^(BOOL contextDidSave, NSError * _Nullable error) {
                [self.dataset removeAllObjects];
                [self.tableview reloadData];
            }];
        }
    }];
}

- (IBAction)onAdd:(id)sender
{
    NSString *name = _cmb_name.stringValue;
    NSString *content = _tf_jiangpin.stringValue;
    NSString *instuction = _tf_instruction.stringValue;
    NSString *tc = _cmb_total_count.stringValue;
    NSString *nums = _cmb_nums_of_per.stringValue;
    
    name = [name stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    content = [content stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    instuction = [instuction stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    if (name.length == 0) {
        [LuckyUtils lucky_show:@"请输入姓名"];
        [_cmb_name becomeFirstResponder];
        return;
    }
    
    if (content.length == 0) {
        [LuckyUtils lucky_show:@"请输入手机号"];
        [_tf_jiangpin becomeFirstResponder];
        return;
    }
    
    BOOL nbtc = [LuckyUtils isNumber:tc];
    
    if (!nbtc) {
        [LuckyUtils lucky_show:@"输入非法，必数为数字"];
        [_cmb_total_count becomeFirstResponder];
        return;
    }
    
    nbtc = [LuckyUtils isNumber:nums];
    
    if (!nbtc) {
        [LuckyUtils lucky_show:@"输入非法，必数为数字"];
        [_cmb_nums_of_per becomeFirstResponder];
        return;
    }
    
    NSControlStateValue st = _ckb_allows.state;
    
    BOOL check = (st == NSControlStateValueOn);
    
    NSString *pno = [LuckyUtils uuid16];
    
    [MagicalRecord saveWithBlock:^(NSManagedObjectContext * _Nonnull localContext) {
        ScenePrizes *add = [ScenePrizes MR_createEntityInContext:localContext];
        add.prizeNo = pno;
        add.prizeName = name;
        add.prizeContent = content;
        add.prizeInstruction = instuction;
        add.isAll = check;
        add.createTime = [NSDate date];
        add.prize_total_count = [tc intValue];
        add.prize_nums_per = [nums intValue];
        add.prize_remain_count = [tc intValue];
    } completion:^(BOOL contextDidSave, NSError * _Nullable error) {
        NSLog(@"保存 %d,error = %@",contextDidSave,error);
        ScenePrizes *newadd = [ScenePrizes MR_findFirstByAttribute:@"prizeNo" withValue:pno];
        if (newadd) {
            [self.dataset insertObject:newadd atIndex:0];
            [self.tableview reloadData];
        }
        [self reset];
    }];
}

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
{
    return self.dataset.count;
}

- (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row
{
    return 30;
}

- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
    NSUserInterfaceItemIdentifier idf = tableColumn.identifier;
    NSTableCellView *cv = [tableView makeViewWithIdentifier:idf owner:nil];
    NSInteger colidx = [tableView columnWithIdentifier:idf];
    
    ScenePrizes *prize = self.dataset[row];
    
    switch (colidx) {
        case 0:
        {
            [cv.textField setStringValue:prize.prizeNo?:@""];
        }
            break;
        case 1:
        {
            [cv.textField setStringValue:prize.prizeName?:@""];
        }
            break;
        case 2:
        {
            [cv.textField setStringValue:prize.prizeContent?:@""];
        }
            break;
        case 3:
        {
            [cv.textField setStringValue:prize.prizeInstruction?:@""];
        }
            break;
        case 4:
        {
            [cv.textField setStringValue:[NSString stringWithFormat:@"%d",prize.prize_nums_per]];
        }
            break;
        case 5:
        {
            [cv.textField setStringValue:[NSString stringWithFormat:@"%d",prize.prize_total_count]];
        }
            break;
        case 6:
        {
            [cv.textField setStringValue:[NSString stringWithFormat:@"%d",prize.prize_remain_count]];
        }
            break;
        case 7:
        {
            [cv.textField setStringValue:prize.stateString?:@""];
        }
            break;
        case 8:
        {
            [cv.textField setStringValue:prize.isAll?@"允许中奖的参与":@"已中奖的不能参与"];
        }
            break;
        default:
            break;
    }
    
    return cv;
}

- (void)menuNeedsUpdate:(NSMenu*)menu
{
    NSInteger idx = self.tableview.selectedRow;
    if (idx == -1) {
        return;
    }
    [menu removeAllItems];
    ScenePrizes *selected = self.dataset[idx];
    if (selected) {
        // 在这里动态添加 menu item
        NSMenuItem *item = [[NSMenuItem alloc]initWithTitle:@"删除" action:@selector(onDeleteClickedRow:) keyEquivalent:@""];
        item.enabled = (selected.prize_remain_count == selected.prize_total_count);
        [menu addItem:item];
        item = [[NSMenuItem alloc]initWithTitle:@"投影仪开奖方式" action:@selector(onProjectorStyle:) keyEquivalent:@""];
        item.enabled = (selected.prize_remain_count != 0);
        [menu addItem:item];
        item = [[NSMenuItem alloc]initWithTitle:@"大屏方式" action:@selector(onBigScreenStyle:) keyEquivalent:@""];
        item.enabled = (selected.prize_remain_count != 0);
        [menu addItem:item];
        
        [menu setAutoenablesItems:NO];
    }
}

- (void)onDeleteClickedRow:(id)sender
{
    ScenePrizes *selected = self.dataset[self.tableview.selectedRow];
    
    [MagicalRecord saveWithBlock:^(NSManagedObjectContext * _Nonnull localContext) {
        NSPredicate *pre = [NSPredicate predicateWithFormat:@"prizeNo = %@",selected.prizeNo];
        [ScenePrizes MR_deleteAllMatchingPredicate:pre inContext:localContext];
    } completion:^(BOOL contextDidSave, NSError * _Nullable error) {
        [self.dataset removeObject:selected];
        [self.tableview reloadData];
    }];
}

- (void)onProjectorStyle:(id)sender
{
    
}

- (void)onBigScreenStyle:(id)sender
{
    NSInteger idx = self.tableview.selectedRow;
    if (idx == -1) {
        return;
    }

    ScenePrizes *selected = self.dataset[idx];
    
    if (!self.scnwnd) {
        self.scnwnd = [[ScencScreenWND alloc]initWithWindowNibName:@"ScencScreenWND"];
    }
    
    ///提取可以中奖的名额人员
    NSInteger st = -1;
    NSArray *persons = [self shouldGoToPrize:selected withState:&st];
    
    if (persons.count == 0) { //都没有人开啥呢。
        [LuckyUtils lucky_show:@"没有找到符合条件的参与人"];
        return;
    }
    
    if (st == 1000) {
        [LuckyUtils lucky_showAlert:@"参与人数不足" info:@"是否确认开奖?" inWindow:self.view.window completed:^(NSInteger result) {
            if (result == NSAlertFirstButtonReturn) {
                ///设置合法的参与人
                self.scnwnd.joinmembers = persons;
                self.scnwnd.style = ScreenStyleWideScreen;
                self.scnwnd.currentprize = selected;
                [self.scnwnd.window center];
                [self.scnwnd showWindow:nil];
            }
        }];
        return;
    }
    
    if (st == 0) {
        ///设置合法的参与人
        self.scnwnd.joinmembers = persons;
        self.scnwnd.style = ScreenStyleWideScreen;
        self.scnwnd.currentprize = selected;
        [self.scnwnd.window center];
        [self.scnwnd showWindow:nil];
    }
}

///判断是否符合抽奖条件
- (NSArray *)shouldGoToPrize:(ScenePrizes *)preparePrize withState:(NSInteger *)state
{
    if (!preparePrize) {
        *state = -1;
        return nil;
    }
    
    NSArray *persons = nil;
    *state = 0;//OK 满足条件
    if (preparePrize.isAll) { //允许所有人参与
        persons = [ScencMembers MR_findAll];
        if (persons.count < preparePrize.prize_nums_per) { //如果参与人小于开奖中奖人数
            *state = 1000; //人数过少，可以增加是否开奖判断
        }
    } else { //踢除已中奖的
        ///从中奖的名单中提取出已中奖的名额
        NSArray *luckystars = [ScencResults MR_findAll];
        
        NSPredicate *pre = [NSPredicate predicateWithFormat:@"not (mid in %@)",[luckystars valueForKey:@"memberid"]];
        
        persons = [ScencMembers MR_findAllWithPredicate:pre];
        
        if (persons.count < preparePrize.prize_nums_per) { //如果参与人小于开奖中奖人数
            *state = 1000; //人数过少，可以增加是否开奖判断
        }
    }
    
    return persons;
}




- (void)windowWillClose:(NSNotification *)notification
{
    NSWindow* window = notification.object;
    if (window == self.scnwnd.window) {
        self.scnwnd = nil;
    }
}



@end
